<template>
  <div class="">
    <div class="myarticles_padding" v-show="hasSelectedItems">
      <div class="myarticles_top">
        <div class="myarticles_top_left">已选择{{ selectedCount }}项</div>
        <div class="myarticles_top_right">
          <button class="top_right_list on" @click="checkSelected" :disabled="!hasSelectedItems">批量审核</button>
          <button class="top_right_list" @click="deleteSelected" :disabled="!hasSelectedItems">批量删除</button>
          <div class="top_right_list" @click="cancelSelection">取消选择</div>
        </div>
      </div>
    </div>
    <div class="myarticles_content toBereviewed">
      <div class="myarticles_content_title">
        <div class="content_title_list">
          <label>
            <input type="checkbox" v-model="selectAll">
            序号
          </label>
        </div>
        <div class="content_title_list">分类</div>
        <div class="content_title_list">标题</div>
        <div class="content_title_list">审核状态</div>
        <div class="content_title_list">创作时间</div>
        <div class="content_title_list">操作</div>
      </div>
      <div class="myarticles_content_tab">
        <div class="content_tab_list" :class="{ on: info.checked }" v-for="(info, index) in infos.data" :key="index">
          <div class="tab_list_li">
            <label>
              <input type="checkbox" v-model="info.checked">
              {{ info.id }}
            </label>
          </div>
          <div class="tab_list_li">{{ info.articleClass.name }}</div>
          <div class="tab_list_li" @click="preCheck(info.id)"><span class="list_li_btn">{{ info.name }}</span></div>
          <div class="tab_list_li ApprovalStatus"><span></span>待审核</div>
          <div class="tab_list_li">{{ info.create_time }}</div>
          <div class="tab_list_li operate">
            <div class="list_li_btn" @click="preview(info.id)"><img src="@a/img/sv9.svg"/>预览</div>
            <div class="list_li_btn" @click="toEditor(info.id)"><img src="@a/img/sv5.svg"/>编辑</div>
            <div class="list_li_btn" @click="preCheck(info.id)"><img src="@a/img/sv10.svg"/>审核</div>
          </div>
        </div>
        <div class="not_data not_data2" v-show="infos.data.length === 0">
          <div class="not_data_icon"><img src="@a/img/bg26.jpg"/></div>
          <div class="not_data_title">暂无创作任务，点击批量<router-link to="/writing/titleGeneration" class="data_title_btn">创作标题</router-link></div>
        </div>
      </div>
    </div>
    
    
    <!-- 预览 -->
		<div class="Preview" v-show="showPreview">
			<div class="Preview_content">
				<div class="Preview_content_title">
					<div class="content_title_left"><span></span>预览</div>
					<div class="content_title_right" @click="showPreview = !showPreview"><i class="el-icon-close"></i>
					</div>
				</div>
				<div class="Preview_content_txt">
					<div class="content_txt_title"> {{editorData.name }}</div>
					<div ref="htmlContent" v-html="editorData.content"></div>
					<div class="content_txt_title2" v-if="editorData.keywords"> 关键词：{{editorData.keywords }}</div>
				</div>
        <div class="Preview_content_btn">
          <div class="content_btn_list close" @click="showPreview = !showPreview">关闭</div>
          <div class="content_btn_list copy" @click="copyHtml">复制</div>
        </div>
			</div>
		</div>


    <!-- 编辑 -->
    <div class="Preview Edit" v-show="showEdit">
      <div class="Preview_content">
        <div class="Preview_content_title">
          <div class="content_title_left"><span></span>编辑</div>
          <div class="content_title_right" @click="showEdit = !showEdit"><i class="el-icon-close"></i></div>
        </div>
        <div class="Edit_content">
          <div class="Edit_content_list">
            <div class="content_list_dd">审核</div>
            <div class="content_list_dt">
              <el-input placeholder="请输入内容" v-model="editorData.name" clearable>
              </el-input>
            </div>
          </div>
          <div class="Edit_content_list">
            <div class="content_list_dd">审核</div>
            <div class="content_list_dt">
              <el-select v-model="editorData.article_class_id" placeholder="默认分类">
                <el-option
                    v-for="item in class_types"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="Edit_content_list Edit_content_txt">
            <div class="content_list_dd">内容</div>
            <div class="content_list_dt">
              <Editor api-key="uzmcaumu2y7g9r2etb3dbozjg2tljvaktxze4e3hptkrjul0" id="tinymceId" v-model="editorData.content" :init="initEditor"></Editor>
            </div>
          </div>
        </div>
        <div class="Edit_btn">
          <button @click="editorSave">保存</button>
        </div>
      </div>
    </div>


    <!-- 审核 -->
    <div class="Preview Review" v-show="showReview">
      <div class="Preview_content">
        <div class="Preview_content_title">
          <div class="content_title_left"><span></span>审核</div>
          <div class="content_title_right" @click="showReview = !showReview"><i class="el-icon-close"></i></div>
        </div>
        <div class="Preview_content_txt">
          <div class="content_txt_title"> {{editorData.name }}</div>
          <div v-html="editorData.content"></div>
        </div>
        <div class="Review_btn">
          <button @click="checkArticle">审核通过</button>
        </div>
      </div>
    </div>

    <!-- 审核进度条 -->
    <div class="ProgressBar" v-if="show">
      <div class="ProgressBar_icon">
        <el-progress :text-inside="true" :stroke-width="60" :percentage="progress" :color="colors"
                     status="success"></el-progress>
      </div>
    </div>


    <div class="page">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="infos.current_page"
          :page-sizes="infos.per_pages"
          :page-size="infos.per_page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="infos.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {MessageBox, Message} from 'element-ui';
import {Notification} from 'element-ui';
import axios from 'axios';
import Editor from "@tinymce/tinymce-vue";

export default {
  name: "toBereviewed",
  props: {
    infos: {
      type: Object,
      default: {
        data: [],
        per_page: 20,
        current_page: 1,
        last_page: 1,
        total: 0
      },
    },
  },
  data() {
    return {
      input: '网站文案策划：如何制定文案目标指南',
      showPreview: false,
      showEdit: false,
      showReview: false,
      content: '',
      per_pages: [20, 50, 100 , 200],

      initEditor: {
        selector: '#tinymceId',
        language: "zh_CN",
        height: 430,
        menubar: false,
        toolbar: 'undo redo | formatselect | bold italic backcolor | \
            alignleft aligncenter alignright alignjustify | \
            bullist numlist outdent indent | removeformat '
      },
      class_types: [],
      editorData:{
        id: 0,
        name: '',
        content: '',
        article_class_id: 0
      },


      progress: 0,
      colors: [
        {color: '#3662eb'},
      ],
      timer: null,
      messages: [
        {title: 'Title 1', message: 'Message 1'},
        {title: 'Title 2', message: 'Message 2'},
        {title: 'Title 3', message: 'Message 3'}
      ],
      show: false,
    };
  },
  components: {
    Editor
  },
  computed: {

    //全选
    selectAll: {
      get() {
        return this.infos.data.every(info => info.checked)
      },
      set(value) {
        this.infos.data.forEach(info => {
          info.checked = value
        })
      },
    },
    selectedCount() {
      return this.infos.data.filter(info => info.checked).length
    },
    allCount() {
      return this.infos.data.filter(info => info).length
    },
    hasSelectedItems() {
      return this.infos.data.filter(info => info.checked).length > 0;
    },
  },

  methods: {
		//复制
		copyHtml() {
		const htmlElement = this.$refs.htmlContent
		const range = document.createRange()
		range.selectNode(htmlElement)
		window.getSelection().removeAllRanges()
		window.getSelection().addRange(range)
		document.execCommand('copy')
		window.getSelection().removeAllRanges()
		this.$message.success('已复制到剪贴板')
		},
    checkArticle(){
      let that = this;
     let  ids = [that.editorData.id];
      that.axios.post('/api/article/setChecked', {
        ids: ids
      }).then(res => {
        if (res.code === 1) {
          that.$emit('refresh')
          that.showReview = false;
          Message.success('审核成功')
        }

      })
    },
    preview(id) {
      let that = this;
      let callback = () => {
        that.showPreview = !that.showPreview
      }
      that.getArticleClass();
      that.getEditorData(id, callback)
    },
    toEditor(id) {
      let that = this;
      let callback = () => {
        that.showEdit = true
      }
      that.getArticleClass();
      that.getEditorData(id, callback)
    },
    preCheck(id) {
      let that = this;
      let callback = () => {
        that.showReview = !that.showReview
      }
      that.getEditorData(id, callback)
    },
    getContent(id, callback) {
      let that = this;
      that.axios.get('/api/article/getContent', {
        params: {
          id: id
        }
      }).then(res => {
        if (res.code == 1) {
          that.content = res.result.content
          callback()
        }
      })
    },
    getArticleClass() {
      let that = this;
      this.axios.get('/api/articleClass/list').then(res => {
        res.result.forEach(item => {
          item.isActive = false
        })
        that.class_types = res.result
      })
    },
    getEditorData(id, callback){
      let that = this;
      that.axios.get('/api/article/getEditor', {
        params: {
          id: id
        }
      }).then(res => {
        if (res.code == 1) {
          that.editorData = res.result
          callback()
        }
      })
    },
    editorSave(){
      let that = this;
      that.axios.post('/api/article/editor', that.editorData).then(res => {
        if(res.code == 1) {
          that.$message.success('保存成功');
          that.$emit("refresh")
          that.showEdit = false
        }
      })
    },


    //分页
    handleSizeChange(val) {
      this.$emit('changeSize', val)
    },
    handleCurrentChange(val) {
      this.$emit('changePage', val)
    },
    //取消选择
    cancelSelection() {
      this.selectAll = false;
    },

    checkSelected() {
      let ids = []
      for (let i = this.infos.data.length - 1; i >= 0; i--) {
        if (this.infos.data[i].checked) {
          ids.push(this.infos.data[i].id)
        }
      }
      let that = this;
      that.axios.post('/api/article/setChecked', {
        ids: ids
      }).then(res => {
        if (res.code === 1) {
          that.$emit('refresh')
          Message.success('审核成功')
        }

      })
    },

    //批量删除
    deleteSelected() {
      let that = this;
      let ids = []
      for (let i = this.infos.data.length - 1; i >= 0; i--) {
        if (this.infos.data[i].checked) {
          ids.push(this.infos.data[i].id)
        }
      }
      MessageBox.confirm(`确定删除文章吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.axios.post('/api/article/delete', {ids: ids}).then(
            (res) => {
              if (res.code === 1) {
                that.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                that.$emit('refresh')
              }

            }
        )
        this.selectAll = false;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
        // 用户点击取消或者弹窗关闭时不做任何操作
      });
    },
    //进度
    loadData() {
      // 快速加载1%到80%
      for (let i = 1; i <= 80; i++) {
        setTimeout(() => {
          this.progress = i;
        }, i * 50);
      }
      // 缓慢加载80%到99%
      for (let i = 81; i <= 99; i++) {
        setTimeout(() => {
          this.progress = i;
        }, i * 100);
      }
    },
    ClickProgress() {
      this.show = !this.show;

      this.loadData();

      // 直接设置进度为100%
      axios.interceptors.request.use(config => {
        this.progress = 0;
        return config;
      });
      axios.interceptors.response.use(response => {
        this.progress = 100;
        if (response.data && response.data.length > 0) {
          this.data = response.data;
        }
        return response;
      }, error => {
        this.progress = 100;
        console.log(error);
        return Promise.reject(error);
      });
      axios.get('http://api.gpt.jijinweb.com/test.php?s=5')
          .catch(error => {
            console.log(error);
          });

      this.timer = setInterval(() => {
        if (this.messages.length > 0) {
          const msg = this.messages.shift();
          Notification({
            title: msg.title,
            message: msg.message
          });
        } else {
          clearInterval(this.timer);
        }
      }, 1000);
    }
  },
}
</script>

<style>
@import "toBereleased.css";
</style>
